//package com.yunxin.core.controller;
//
//import cn.hutool.core.util.StrUtil;
//import com.yunxin.common.exception.BusinessException;
//import com.yunxin.common.result.Result;
//import com.yunxin.common.utils.JacksonUtils;
//import com.yunxin.core.application.dto.product.ProductInfoDTO;
//import com.yunxin.core.application.seceiver.message.ProductStatistics;
//import com.yunxin.core.application.service.ProductQueryGatewayService;
//import com.yunxin.core.domain.model.order.OrderUserApply;
//import com.yunxin.core.domain.model.order.OrderUserApplyAllocation;
//import com.yunxin.core.domain.service.order.OrderService;
//import com.yunxin.core.domain.service.order.impl.OrderStatisticsHandle;
//import com.yunxin.core.domain.service.order.impl.OrderUserAllocationMatchHandle;
//import com.yunxin.core.domain.service.order.impl.OrderUserApplyAllocationStockHandle;
//import com.yunxin.core.dto.AbutmentWechatDTO;
//import com.yunxin.core.dto.CancelReqDTO;
//import com.yunxin.core.infra.common.order.enums.OrderLockKey;
//import com.yunxin.core.infra.persistence.entity.user.UserInfoDO;
//import com.yunxin.core.infra.persistence.mapper.user.UserInfoMapper;
//import com.yunxin.core.utils.infra.common.constant.RedisConstants;
//import com.yunxin.core.utils.infra.support.lock.DistributedLock;
//import com.yunxin.core.utils.infra.support.lock.DistributedLockFactory;
//import com.yunxin.point.domain.external.PointExternalService;
//import com.yunxin.point.domain.external.SaveUserBuryingPointData;
//import com.yunxin.point.infra.common.UserBuryingPointTypeEnum;
//import com.yunxin.statistics.infra.common.ProductStatisticsTypeEnum;
//import com.yunxin.statistics.infra.common.PromotionStatisticsTypeEnum;
//import io.swagger.v3.oas.annotations.tags.Tag;
//import lombok.RequiredArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.web.bind.annotation.PostMapping;
//import org.springframework.web.bind.annotation.RequestBody;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;
//
//import java.util.List;
//import java.util.Objects;
//import java.util.concurrent.TimeUnit;
//
//@Slf4j
//@Tag(name = "企业微信回调")
//@RestController
//@RequestMapping("/partners/Wechat")
//@RequiredArgsConstructor
//public class AbutmentWechat {
//
//    private final OrderService orderService;
//
//
//    private final OrderStatisticsHandle orderStatisticsHandle;
//
//    @Value("${allocation.default.productId}")
//    private Long allocationDefaultProductId;
//
//    @Value("${allocation.default.merchantId}")
//    private Long allocationDefaultMerchantId;
//
//    private final PointExternalService pointExternalService;
//
//    private final ProductQueryGatewayService productQueryGatewayService;
//
//    private final OrderUserApplyAllocationStockHandle orderUserApplyAllocationStockHandle;
//
//
//    private final DistributedLockFactory distributedLockFactory;
//
//
//    private final UserInfoMapper userInfoMapper;
//
//    private final RedisTemplate<String, Object> redisTemplate;
//
//    private final OrderUserAllocationMatchHandle orderUserAllocationMatchHandle;
//
//
//    @PostMapping("/zhzx")
//    public Result<?> zhzx(@RequestBody AbutmentWechatDTO dto) {
//        OrderUserApply userApply = dto.getUserApply();
//
//        // 分布式锁 用户code为key
//        DistributedLock lock = distributedLockFactory.provideDistributedLock(OrderLockKey.QW_USER_STACK_KEY.getPrefix() + userApply.getUserCode());
//        if (lock.tryLock(OrderLockKey.QW_USER_STACK_KEY.getWaitTime(), OrderLockKey.QW_USER_STACK_KEY.getReleaseTime(), OrderLockKey.QW_USER_STACK_KEY.getTimeUnit())) {
//
//            // 先查redis
//            String key = RedisConstants.INSTANCE.of(RedisConstants.ABUTMENT_TYPE, dto.getUserPhone(),dto.getOrderUserApplyAllocation().getProductId().toString());
//            String val = (String) redisTemplate.opsForValue().get(key);
//            try {
//                // 防止多次发消息
//                if (StrUtil.isEmpty(val)) {
//                    // 锁产品
//                    DistributedLock stockLock = distributedLockFactory.provideDistributedLock(OrderLockKey.QW_PRODUCT_STACK_KEY.getPrefix() + dto.getOrderUserApplyAllocation().getProductId());
//                    try {
//                        if (lock.tryLock(OrderLockKey.QW_PRODUCT_STACK_KEY.getWaitTime(), OrderLockKey.QW_PRODUCT_STACK_KEY.getReleaseTime(), OrderLockKey.QW_PRODUCT_STACK_KEY.getTimeUnit())) {
//                            // 检查库存
//                            boolean b = orderUserApplyAllocationStockHandle.checkProductStock(dto.getOrderUserApplyAllocation().getProductId(), dto.getTotalLimit());
//                            if (!b) {
//                                //库存不足
//                                log.warn("产品库存不足,productId={}", dto.getOrderUserApplyAllocation().getProductId());
//                                return Result.success();
//                            }
//                            // 企微产品加一
//                            orderUserApplyAllocationStockHandle.determineProductStock(dto.getOrderUserApplyAllocation().getProductId());
//                            OrderUserApplyAllocation applyAllocation = dto.getOrderUserApplyAllocation();
//                            orderService.saveOrderUserApplyAllocation(dto.getUserApply(), applyAllocation, dto.getRedisCashField());
//                            allocationOrderSuccess(dto.getOrderUserApplyAllocation(), dto.getUserApply(), dto.getSex(), dto.getClientIp());
//                            // 存redis
//                            redisTemplate.opsForValue().set(key, dto.getUserPhone(), 20, TimeUnit.MINUTES);
//                        }
//                    } finally {
//                        log.info("释放锁成功！{}", dto.getOrderUserApplyAllocation().getProductId());
//                        stockLock.unlock();
//                    }
//                }
//            } finally {
//                log.info("释放锁成功！{}", userApply.getChannelPromotionCode());
//                lock.unlock();
//            }
//        } else {
//            log.info("订单no={},渠道code={},重复提交", userApply.getApplyOrderNo(), userApply.getChannelPromotionCode());
//            throw new BusinessException("请勿频繁操作,稍后再试");
//        }
//        return Result.success();
//    }
//
//    @PostMapping("/fqd")
//    public Result<?> fqd(@RequestBody AbutmentWechatDTO dto) {
//        // 先查一下分配单存在不存在
//        OrderUserApply userApply = dto.getUserApply();
//        DistributedLock lock = distributedLockFactory.provideDistributedLock(OrderLockKey.QW_BE_USER_STACK_KEY.getPrefix() + userApply.getUserCode());
//        if (lock.tryLock(OrderLockKey.QW_BE_USER_STACK_KEY.getWaitTime(), OrderLockKey.QW_BE_USER_STACK_KEY.getReleaseTime(), OrderLockKey.QW_BE_USER_STACK_KEY.getTimeUnit())) {
//            try {
//                // 先查redis
//                String key = RedisConstants.INSTANCE.of(RedisConstants.BE_ABUTMENT_TYPE, dto.getUserPhone(),dto.getProductId().toString());
//                String val = (String) redisTemplate.opsForValue().get(key);
//                // 防止多次发消息
//                if (StrUtil.isEmpty(val)) {
//                    // 锁产品
//                    DistributedLock stockLock = distributedLockFactory.provideDistributedLock(OrderLockKey.QW_PRODUCT_BE_STACK_KEY.getPrefix() + dto.getProductId());
//                    try {
//                        if (lock.tryLock(OrderLockKey.QW_PRODUCT_BE_STACK_KEY.getWaitTime(), OrderLockKey.QW_PRODUCT_BE_STACK_KEY.getReleaseTime(), OrderLockKey.QW_PRODUCT_BE_STACK_KEY.getTimeUnit())) {
//                            // 检查库存
//                            boolean b = orderUserApplyAllocationStockHandle.checkProductStock(dto.getProductId(), dto.getTotalLimit());
//                            if (!b) {
//                                //库存不足
//                                log.warn("产品库存不足,productId={}", dto.getProductId());
//                                return Result.success();
//                            }
//                            ProductInfoDTO result = productQueryGatewayService.getProductInfo(dto.getProductId());
//                            OrderUserApplyAllocation applyAllocation = dto.getOrderUserApplyAllocation();
//                            userApply.setProductId(dto.getProductId());
//                            applyAllocation.setProductId(dto.getProductId());
//                            applyAllocation.setMerchantId(result.getMerchantId());
//                            //重新分配
//                            Long allocationId = orderUserAllocationMatchHandle.allocationMerchantAccountId(result.getMerchantId());
//                            applyAllocation.setCurrentAccountId(allocationId);
//                            // 保存分配单
//                            orderService.saveOrderUserApplyAllocation(dto.getUserApply(), applyAllocation, dto.getRedisCashField());
//
//                            // 前置产品加一
//                            orderUserApplyAllocationStockHandle.determineProductStock(dto.getProductId());
//                            // 订单分配成功处理
//                            allocationOrderSuccess(dto.getOrderUserApplyAllocation(), dto.getUserApply(), dto.getSex(), dto.getClientIp());
//                            // 存redis
//                            redisTemplate.opsForValue().set(key, dto.getUserPhone(), 20, TimeUnit.MINUTES);
//                            // 标记该用户 表示已经分配过企微的前置产品，后续前置产品只是腰带钱包
//                            UserInfoDO userInfoDO = userInfoMapper.selectByUserCode(userApply.getUserCode());
//                            userInfoDO.setIsAbutment(1);
//                            userInfoMapper.updateByPrimaryKey(userInfoDO);
//                        }
//                    } finally {
//                        log.info("释放锁成功！{}", dto.getOrderUserApplyAllocation().getProductId());
//                        stockLock.unlock();
//                    }
//                }
//            } finally {
//                log.info("释放锁成功！{}", userApply.getChannelPromotionCode());
//                lock.unlock();
//            }
//        } else {
//            log.info("订单no={},渠道code={},重复提交", userApply.getApplyOrderNo(), userApply.getChannelPromotionCode());
//            throw new BusinessException("请勿频繁操作,稍后再试");
//        }
//        return Result.success();
//    }
//
//    /**
//     * 取消按钮
//     *
//     * @param dto
//     * @return
//     */
//    @PostMapping("/cancel")
//    public Result<?> cancel(@RequestBody CancelReqDTO dto) {
//        // 在这里判断
//        UserInfoDO userInfoDO = userInfoMapper.selectByUserCode(dto.getUserCode());
//        // 判断是否已经申请过企微的前置产品
//        if (userInfoDO.getIsAbutment().equals(1)) {
//            return Result.success(1);
//        }
//        return Result.success(2);
//
//    }
//
//
//    private void allocationOrderSuccess(OrderUserApplyAllocation orderUserApplyAllocation, OrderUserApply userApply, Integer sex, String clientIp) {
//        if (Objects.nonNull(orderUserApplyAllocation.getProductId())) {
//            // 产品转化统计
//            ProductStatistics productStatistics = new ProductStatistics();
//            productStatistics.setProductId(orderUserApplyAllocation.getProductId());
//            productStatistics.setMerchantId(orderUserApplyAllocation.getMerchantId());
//            productStatistics.setProductPrice(orderUserApplyAllocation.getProductPrice());
//            productStatistics.setType(ProductStatisticsTypeEnum.ALLOCATION_ORDER);
//            productStatistics.setUserName(orderUserApplyAllocation.getUserName());
//            productStatistics.setUserPhone(orderUserApplyAllocation.getUserPhone());
//            productStatistics.setSex(sex);
//            // mq发消息
//            orderStatisticsHandle.statisticsProductTransform(productStatistics);
//            //调用渠道推广转化统计
//            if (orderUserApplyAllocation.getProductId().equals(allocationDefaultProductId)) {
//                orderStatisticsHandle.statisticsChannelPromotionTransform(userApply.getChannelId(), userApply.getChannelPromotionCode(),
//                        orderUserApplyAllocation.getChannelPromotionPrice(), orderUserApplyAllocation.getProductPrice(), PromotionStatisticsTypeEnum.FROM_INFERIOR);
//            } else {
//                orderStatisticsHandle.statisticsChannelPromotionTransform(userApply.getChannelId(), userApply.getChannelPromotionCode(),
//                        orderUserApplyAllocation.getChannelPromotionPrice(), orderUserApplyAllocation.getProductPrice(), PromotionStatisticsTypeEnum.FROM);
//            }
//            //用户分配统计
//            orderStatisticsHandle.statisticsUserAllocation(userApply.getUserCode(), orderUserApplyAllocation.getAllocationTime());
//            // 分配埋点
//            SaveUserBuryingPointData saveUserBuryingPointData = new SaveUserBuryingPointData();
//            saveUserBuryingPointData.setVisitorId(userApply.getVisitorId());
//            saveUserBuryingPointData.setIp(clientIp);
//            saveUserBuryingPointData.setUserCode(userApply.getUserCode());
//            saveUserBuryingPointData.setBuryingPointTypeEnum(UserBuryingPointTypeEnum.ORDER_APPLY_ALLOCATION);
//            saveUserBuryingPointData.setData(JacksonUtils.X.format(orderUserApplyAllocation));
//            pointExternalService.saveUserBuryingPointData(saveUserBuryingPointData);
//        }
//
//    }
//
//}
